package com.xz.spi.javassit;

import com.xz.simplerpc.api.DemoService;
import javassist.*;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;

/**
 * Created by FangXz on 2017/11/8.
 */
public class JavassitDemo2 {
    public static void main(String[] args) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.makeClass(DemoService.class.getCanonicalName() + "$Adaptive");
        try {
            ctClass.addInterface(pool.get(DemoService.class.getCanonicalName()));
            Method[] methods = DemoService.class.getMethods();

            for(Method method : methods) {
                Class<?> rt = method.getReturnType();
                Class<?>[] pts = method.getParameterTypes();
                Class<?>[] ets = method.getExceptionTypes();
                // e.g. public String hello(String arg0) { return null; }
                StringBuffer methodBuffer = new StringBuffer("public ");
                methodBuffer.append(rt.getCanonicalName()).append(" ");
                methodBuffer.append(" ").append(method.getName()).append("(");
                if(ArrayUtils.isNotEmpty(pts)) {
                    for (int i=0; i<=pts.length-1; i++) {
                        if(i>0) methodBuffer.append(",");
                        methodBuffer.append(pts[i].getName()).append(" ").append("arg"+i);
                    }
                }
                methodBuffer.append(")");
                if(ArrayUtils.isNotEmpty(ets)) {
                    methodBuffer.append(" throws ");
                    for (int i=0; i<=ets.length-1; i++) {
                        if(i>0) methodBuffer.append(",");
                        methodBuffer.append(ets[i].getName());
                    }
                }
                methodBuffer.append("{ ");
                if(!"void".equals(rt.getName())) {
                    methodBuffer.append("return null;");
                }
                methodBuffer.append(" }");

                ctClass.addMethod(CtMethod.make(methodBuffer.toString(), ctClass));
            }
            ctClass.writeFile("D:\\git source\\simple-rpc\\dubbo-simplerpc");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
